import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/x3_component_core.dart';

/// 编辑页面
class BaseFormEditScreen extends StatefulWidget {
  final BaseHttpRequestModel request;

  ///是否是多行文本输入
  final bool isMultipleLines;

  const BaseFormEditScreen({Key key, @required this.request, this.isMultipleLines = false}) : super(key: key);

  @override
  _BaseFormEditScreenState createState() => _BaseFormEditScreenState();
}

class _BaseFormEditScreenState extends State<BaseFormEditScreen> {
  String _editText;

  BaseHttpRequestModel get request => widget.request;

  @override
  Widget build(BuildContext context) {
    return BaseScaffoldComponent(
      willPopScope: _willPopScope,
      backGroundColor: Colors.white,
      title: request.name,
      child: _buildContent(request),
    );
  }

  Future<bool> _willPopScope() {
    FocusScope.of(context).requestFocus(FocusNode());
    return Future.value(true);
  }

  Widget _buildContent(BaseHttpRequestModel request) {
    return ListView(
      physics: NeverScrollableScrollPhysics(),
      padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
      children: [
        Container(
          decoration: BoxDecoration(
            border: Border.all(color: Color(0xFFF3F3F3)),
            borderRadius: BorderRadius.circular(2),
          ),
          padding: EdgeInsets.only(left: 12.0, top: 2.0),
          child: BaseTextField(
            maxHeight: widget.isMultipleLines ? 80 : 40,
            keyboardType: _inputShowType(),
            value: request.defaultValue,
            maxLines: widget.isMultipleLines ? 10 : 1,
            hintText: request.notes.isNotEmpty ? request.notes : '请输入',
            onChanged: _editTextCallBack,
            textInputAction: TextInputAction.send,
            autoFocus: false,
            onSubmitted: (String value) => {this._onSave()},
          ),
        ),
        SizedBox(height: 12.0),
        BaseButton(
          text: '保存',
          height: 40,
          onPress: _editText == null ? null : ((request.required == true && _editText.length == 0) ? null : _onSave),
        )
      ],
    );
  }

  _editTextCallBack(String text) {
    setState(() => {_editText = text});
  }

  _onSave() {
    String data = _editText == null ? request.defaultValue : _editText;
    if (request.required == true && BaseUtils.isNotEmpty(data) == false) {
      BaseUtils.showToast(request.notes);
      return;
    }
    FocusScope.of(context).requestFocus(FocusNode());
    Navigator.of(context).pop(data);
  }

  /// 键盘类型
  TextInputType _inputShowType() {
    // if (widget.request.showType == BaseHttpShowTypeEnum.Number) return TextInputType.number;
    return null;
  }
}
